/*
 * Project Name spring-boot-tools
 * File Name ActiveTestTask
 * Package Name com.huxiaosu.tools.cmpp.scheduler
 * Create Time 2024/5/12
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.scheduler;

import com.huxiaosu.tools.cmpp.config.CmppClientConfig;
import com.huxiaosu.tools.cmpp.enums.CommandId;
import com.huxiaosu.tools.cmpp.lib.SocketClient;
import com.huxiaosu.tools.cmpp.model.MessageHeader;
import com.huxiaosu.tools.cmpp.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/12 17:40
 */
@Slf4j
@Component
@EnableScheduling
public class ActiveTestTask {

    @Autowired
    private CmppClientConfig cmppClientConfig;

    @Scheduled(cron = "0 0/3 * * * ?")
    public void executeCollectionTask() {
        log.info("<开始链路检查>");
        int count = 0;
        boolean result = activityTestISMG();
        while (!result) {
            count++;
            result = activityTestISMG();
            // 如果再次链路检查次数超过两次则终止连接
            if (count >= (cmppClientConfig.getConnectCount() - 1)) {
                break;
            }
        }
        log.info("<链路检查结束>");
    }

    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public boolean activityTestISMG() {
        boolean result = false;
        try {
            MessageHeader head = new MessageHeader();
            // 消息总长度，级总字节数:4+4+4(消息头)+6+16+1+4(消息主体)
            head.setTotalLength(12);
            // 标识创建连接
            head.setCommandId(CommandId.CMPP_ACTIVE_TEST.getCommand());
            // 序列，由我们指定
            head.setSequenceId(Utils.getSequence());
             SocketClient.getInstance(cmppClientConfig).sendMessage(head.toBytes());
            result = true;
        }
        catch (Exception e) {
            log.error("<链路检查异常>", e);
        }
        return result;
    }

}
